package com.flyu.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.flyu.dao.BaseDao;
import com.flyu.dao.user.UserDao;
import com.flyu.pojo.Role;
import com.flyu.pojo.User;
import com.flyu.service.role.RoleService;
import com.flyu.service.role.RoleServiceImpl;
import com.flyu.service.user.UserServiceImpl;
import com.flyu.util.Constants;
import com.flyu.util.PageSupport;
import com.mysql.cj.util.StringUtils;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("savepwd") && method != null){
            this.updatePwd(req, resp);
        } else if (method.equals("pwdmodify") && method != null){
            this.pwdmodify(req, resp);
        } else if (method.equals("query") && method != null){
            this.query(req, resp);
        } else if (method.equals("add") && method != null){
            this.add(req, resp);
        } else if (method.equals("ucexist") && method != null){
            this.userCodeExist(req, resp);
        } else if (method.equals("getrolelist") && method != null){
            this.getrolelist(req, resp);
        } else if (method.equals("deluser") && method != null){
            this.delUser(req, resp);
        } else if (method.equals("modify") && method != null) {
            this.getUserById(req, resp, "usermodify.jsp");
        }else if (method.equals("modifyexe") && method != null){
            this.modifySave(req, resp);
        } else if (method.equals("view") && method != null){
            this.getUserById(req, resp, "userview.jsp");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    // 更新密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        // 获取前端传来的参数
        String newpassword = req.getParameter("newpassword");
        // 从session中获取当前用户
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);

        boolean flag = false;
        // 如果用户存在且newpassword不为空
        if (o!=null && newpassword!=null){
            UserServiceImpl userService = new UserServiceImpl();    // 向下调用service层
            flag = userService.updatePwd(((User) o).getId(), newpassword);  // 执行service层的updatePwd操作
            if (flag){
                req.setAttribute("message", "密码修改成功，请重新登录");
                // 移除当前session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "密码修改失败");
            }
        } else {
            req.setAttribute("message", "新密码有问题");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 验证旧密码，session中直接获取旧密码
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        // 万能的map，结果集
        Map<String, String> resultMap = new HashMap<String, String>();

        if (o==null){   // session失效
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)){
            resultMap.put("result", "error");
        } else {
            // 先获取session中的密码，然后与输入的旧密码比较
            String userPassword = ((User) o).getUserPassword();
            if (oldpassword.equals(userPassword)){
                resultMap.put("result", "true");
            }else {
                resultMap.put("result", "false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            System.out.println("pwdmodify: "+JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 查询用户记录
    public void query(HttpServletRequest req, HttpServletResponse resp){
        // 获取前端数据
        String queryname = req.getParameter("queryname");
        String tmp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;
        // 获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        // 第一次走这个请求，一定是第一页，页面大小固定
        int pageSize = 5;
        int currentPageNo = 1;

        if (queryname==null){
            queryname="";
        }
        if (tmp!=null && !tmp.equals("")){
            queryUserRole = Integer.parseInt(tmp);
        }
        if (pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        // 获取用户总数（分页：上一页、下一页情况）
        int totalCount = userService.getUserCount(queryname, queryUserRole);
        // 总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = ((int) (totalCount/pageSize))+1;

        // 控制首尾页
        if (currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryname, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryname);
        req.setAttribute("queryUserRole", queryUserRole);

        // 返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        // 从前端获取数据
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String userRole = req.getParameter("userRole");
        String address = req.getParameter("address");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.parseInt(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setUserRole(Integer.parseInt(userRole));
        user.setCreationDate(new Date());
        // 获取当前登录用户的sessionID
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setAddress(address);

        UserServiceImpl userService = new UserServiceImpl();
        boolean flag = userService.addUser(user);

        if (flag){  // 添加成功
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        } else {    // 添加失败
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }

    }
    // 判断userCode是否存在
    public void userCodeExist(HttpServletRequest req, HttpServletResponse resp) {
        String userCode = req.getParameter("userCode");
        Map<String, String> resultMap = new HashMap<String, String>();

        if (!StringUtils.isNullOrEmpty(userCode)){
            UserServiceImpl userService = new UserServiceImpl();
            boolean userCodeExist = userService.userCodeExist(userCode);
            if (userCodeExist){ // 存在
                resultMap.put("userCode", "exist");
            } else {
                resultMap.put("userCode", "no_exist");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    // 查询角色列表
    public void getrolelist(HttpServletRequest req, HttpServletResponse resp){
        // 添加角色列表
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();

        resp.setContentType("application/json");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(JSONArray.toJSONString(roleList));
        writer.flush();
        writer.close();

    }
    // 删除指定用户
    public void delUser(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("进入了delUser");
        int uid = Integer.parseInt(req.getParameter("userid"));
        // 查询是否存在uid
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserById(uid);

        Map<String, String> resultMap = new HashMap<String, String>();

        if (user == null){      // id不存在
            resultMap.put("delResult", "notexist");
        }else {
            boolean isDel = userService.delUser(uid);
            // 删除成功
            if (isDel) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }

        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(JSONArray.toJSONString(resultMap));
        System.out.println("delUser: "+JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();

    }
    // 修改用户信息，先查询展示出来
    public void getUserById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        String uid = req.getParameter("uid");

        if (!StringUtils.isNullOrEmpty(uid)){
            // 调用后台方法得到user
            UserServiceImpl userService = new UserServiceImpl();
            User user = userService.getUserById(Integer.parseInt(uid));
            req.setAttribute("user", user);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }
    // 保存修改
    public void modifySave(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        String id = req.getParameter("uid");
        Object[] params = {userName, gender, birthday, phone, address, userRole, id};
        UserServiceImpl userService = new UserServiceImpl();
        boolean flag = userService.modifySave(params);
        if (flag){
            // 修改保存成功
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }
}
